package com.example.librarymanagementsystembackend.advice;

import com.example.librarymanagementsystembackend.utils.InvalidRequestException;
import com.example.librarymanagementsystembackend.utils.ResponseData;
import com.example.librarymanagementsystembackend.utils.ResponseDataUtils;
import com.example.librarymanagementsystembackend.utils.TerminalFontColor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestControllerAdvice // 等同于 @ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {

    // 处理所有 InvalidRequestException 异常
    @ExceptionHandler(InvalidRequestException.class)
    public ResponseData handleInvalidRequestException(
            InvalidRequestException e,
            HttpServletRequest request) {

        ResponseData responseData = ResponseDataUtils.error(e.getErrorCode(), e.getMessage());
        String YELLOW = TerminalFontColor.YELLOW;
        String RESET = TerminalFontColor.RESET;
        String path =  (String) request.getAttribute("originalPath");
        if (path == null) {
            path = request.getRequestURI();
        }
        System.out.println(
                YELLOW + "[" + LocalDateTime.now() + "] " + RESET
                + request.getMethod() + " " + path + " (业务异常):\n"
                + e.getMessage());
        return responseData;
    }

    // 兜底处理所有其他异常（NullPointerException、SQLException 等）
    @ExceptionHandler(Exception.class)
    public ResponseData handleAllExceptions(Exception e, HttpServletRequest request) {
        String RED = TerminalFontColor.RED;
        String RESET = TerminalFontColor.RESET;
        String path =  (String) request.getAttribute("originalPath");
        if (path == null) {
            path = request.getRequestURI();
        }
        System.out.println(
                RED + "[" + LocalDateTime.now() + "] " + RESET
                + request.getMethod() + " " + path + " (系统异常):");
        e.printStackTrace();
        HttpStatus status = resolveAnnotatedResponseStatus(e);
        Map data = new LinkedHashMap<>();
        data.put("exceptionMessage", e.getMessage());
        data.put("exceptionStackTrace", e.getStackTrace());
        return new ResponseData(status.value(), status.getReasonPhrase(), data);
    }

    private HttpStatus resolveAnnotatedResponseStatus(Exception ex) {
        ResponseStatus annotation = ex.getClass().getAnnotation(ResponseStatus.class);
        return (annotation != null) ? annotation.value() : HttpStatus.INTERNAL_SERVER_ERROR;
    }


}